package com.jason.campusinn.view;

/**
 * Created by yuandian on 2015/5/22.
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PathEffect;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import com.yuandian.wanna.R;
import com.yuandian.wanna.utils.BigStone;
import com.yuandian.wanna.utils.LogUtil;

import android.util.DisplayMetrics;
import java.util.List;
import java.util.ArrayList;

/**
 * 圆盘式的view
 *
 * @author chroya
 *
 */
public class RoundSpinView extends View {
    private Paint mPaint = new Paint();
    private PaintFlagsDrawFilter pfd;

    private int startMenu;   //菜单的第一张图片的资源id

    // stone列表
    //private BigStone[] mStones;
    private List<BigStone> mStones;
    private List<BigStone> mTotalStones;

    // 数目
    //private static final int STONE_COUNT = 12;//TODO

    // 圆心坐标
    private int mPointX = 0, mPointY = 0;
    // 半径
    private int mRadius = 0;
    // 每两个点间隔的角度
    private int mDegreeDelta;

    private int menuRadius; // 菜单的半径

    private int mCur = -1; // 正在被移动的menu;

    private boolean[] quadrantTouched;   //对每个象限触摸情况的记录

    // Touch detection
    private GestureDetector mGestureDetector;

    private onRoundSpinViewListener mListener;  //自定义事件监听器

    private final static int TO_ROTATE_BUTTON = 0;  //旋转按钮；

    private Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TO_ROTATE_BUTTON:
                    float velocity = Float.parseFloat(msg.obj.toString());
                    rotateButtons(velocity/75);
                    velocity /= 1.05F;
                    FlingRunnable(velocity);
                    break;

                default:
                    break;
            }
        };
    };

    public interface onRoundSpinViewListener{
        public void onSingleTapUp(int position, int cur);  //监听每个菜单的单击事件
        public void onSingleTrag(int position);
    }

    public RoundSpinView(Context context,AttributeSet attrs) {
        super(context,attrs);
        if(attrs!=null){
            TypedArray a = getContext().obtainStyledAttributes(attrs,
                    R.styleable.RoundSpinView);
            startMenu = a.getResourceId(R.styleable.RoundSpinView_menuStart, 0);
        }
        pfd = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);
        mPaint.setColor(Color.WHITE);
        mPaint.setStrokeWidth(2);
        mPaint.setAntiAlias(true); //消除锯齿
        mPaint.setStyle(Paint.Style.STROKE); //绘制空心圆
        PathEffect effects = new DashPathEffect(new float[]{5,5,5,5},1);
        mPaint.setPathEffect(effects);


        quadrantTouched = new boolean[] { false, false, false, false, false };
        mGestureDetector = new GestureDetector(getContext(),
                new MyGestureListener());

        //setupStones();
    }

    public void initStonesList(List<BigStone> list, int visible_cnt)
    {
        mTotalStones = list;

        setupStones(visible_cnt);

        initStones();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mPointX = this.getMeasuredWidth()/2;
        mPointY = this.getMeasuredWidth()/2;

        //初始化半径和菜单半径
        mRadius = mPointX-mPointX/5;
        menuRadius = (int)(mPointX/5.5);

        //computeCoordinates();
    }

    /**
     * 初始化每个点
     */
    private void setupStones(int count) {
        //mStones = new BigStone[STONE_COUNT];
        mStones = new ArrayList<BigStone>();
        BigStone stone;
        int angle = 270;//第一个菜单距离水平0度的初始角度

//        if(count<8)
//        {
//            count = 12;
//        } else {
//            if(count>12)
//            {
//                count = 12;
//            }
//        }
        count = 8;

        mDegreeDelta = 360 / count;

        for (int index = 0; index < count; index++) {
            stone = new BigStone();
            if (angle >= 360) {
                angle -= 360;
            }else if(angle < 0){
                angle += 360;
            }
            stone.angle = angle;

//            stone.bitmap = BitmapFactory.decodeResource(getResources(),
//                    startMenu + index);

            angle += mDegreeDelta;
            stone.isVisible = false;

            mStones.add(stone);
//			mStones[index] = stone;
//			
//			//TODO:hide all stones at the beginning
//			mStones[index].isVisible = false;

        }

        //computeCoordinates();
    }

    private void initStones()
    {

        for (int index = 0; index < mStones.size(); index++) {

            if(mStones.get(index).angle>=180&&mStones.get(index).angle<=270&&index<mTotalStones.size())
            {
                mStones.get(index).index = 0;
//                mStones.get(index).bitmap = mTotalStones.get(index).bitmap;
//                mStones.get(index).isFirstShow = false;
            } else {
                mStones.get(index).index = -1;
            }

        }

        invalidate();
    }

    /**
     * 重新计算每个点的角度
     */
    public void resetStonesAngle(float x, float y) {
        int angle = computeCurrentAngle(x, y);
        Log.d("RoundSpinView", "angle:" + angle);
        for (int index = 0; index < mStones.size(); index++) {
            mStones.get(index).angle = angle;
            angle += mDegreeDelta;
        }
    }

    /**
     * 计算每个点的坐标
     */
    private void computeCoordinates() {
        BigStone stone;
        for (int index = 0; index < mStones.size(); index++) {
            stone = mStones.get(index);
            stone.x = mPointX
                    + (float) (mRadius * Math.cos(Math.toRadians(stone.angle)));
            stone.y = mPointY
                    + (float) (mRadius * Math.sin(Math.toRadians(stone.angle)));
        }
    }

    /**
     * 计算某点的角度
     *
     * @param x
     * @param y
     * @return
     */
    private int computeCurrentAngle(float x, float y) {
        float distance = (float) Math
                .sqrt(((x - mPointX) * (x - mPointX) + (y - mPointY)
                        * (y - mPointY)));
        int degree = (int) (Math.acos((x - mPointX) / distance) * 180 / Math.PI);
        if (y < mPointY) {
            degree = -degree;
        }

//        Log.d("RoundSpinView", "x:" + x + ",y:" + y + ",degree:" + degree);
        return degree;
    }

    private double startAngle;

    private boolean isTragIn(int x, int y)
    {
        boolean rtn = false;

        if((Math.abs(x-mPointX)<mRadius/2)&&
                (Math.abs(y-mPointY)<mRadius/2))
        {
            rtn = true;
        }

        return rtn;
    }

    public boolean m_moving = false;
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        // resetStonesAngle(event.getX(), event.getY());
        // computeCoordinates();
        // invalidate();

        int x, y;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            x = (int) event.getX();
            y = (int) event.getY();
            mCur = getInCircle(x, y);
            if (mCur == -1) {
                startAngle = computeCurrentAngle(x, y);
            }
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            x = (int) event.getX();
            y = (int) event.getY();
            if (mCur != -1) {
                mStones.get(mCur).x = x;
                mStones.get(mCur).y = y;
                invalidate();
            } else {
                double currentAngle = computeCurrentAngle(x, y);
                //TODO: 滑动选择
                //rotateButtons(startAngle - currentAngle);
                //if(currentAngle>startAngle)
//				{
//					rotateButtons(currentAngle - startAngle);
//					startAngle = currentAngle;
//				}

                if(!m_moving)
                {
                    m_moving = true;
                    Log.e("ACTION_MOVE", String.valueOf(currentAngle - startAngle));

                    //if(Math.abs(currentAngle - startAngle)<6)
                    {
                        //rotateButtons(currentAngle - startAngle);
                    }

                    if(currentAngle - startAngle>0)
                    {
                       rotateButtons(10);
                    } else {
                        if(currentAngle - startAngle<0)
                        {
                            rotateButtons(-10);
                        }
                    }

                    ////////////rotateButtons(startAngle - currentAngle);
                    startAngle = currentAngle;
                    m_moving = false;
                }


            }
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            x = (int) event.getX();
            y = (int) event.getY();
            if (mCur != -1) {
                computeCoordinates();

                //TODO: if you want to swap the button among each others, uncomment below lines.
//				int cur = getInCircle(x, y);
//				if (cur != mCur && cur != -1) {
//					int angle = mStones[mCur].angle;
//					mStones[mCur].angle = mStones[cur].angle;
//					mStones[cur].angle = angle;
//				}

                if(isTragIn(x,y))
                {
                    mListener.onSingleTrag(mStones.get(mCur).index);
                }

                computeCoordinates();
                invalidate();
                mCur = -1;
            }
        }

        // set the touched quadrant to true
        quadrantTouched[getQuadrant(event.getX() - mPointX,
                mPointY - event.getY())] = true;
        mGestureDetector.onTouchEvent(event);
        return true;
    }

    private class MyGestureListener extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            // get the quadrant of the start and the end of the fling
            int q1 = getQuadrant(e1.getX() - mPointX, mPointY - e1.getY());
            int q2 = getQuadrant(e2.getX() - mPointX, mPointY - e2.getY());

            // the inversed rotations
            if ((q1 == 2 && q2 == 2 && Math.abs(velocityX) < Math
                    .abs(velocityY))
                    || (q1 == 3 && q2 == 3)
                    || (q1 == 1 && q2 == 3)
                    || (q1 == 4 && q2 == 4 && Math.abs(velocityX) > Math
                    .abs(velocityY))
                    || ((q1 == 2 && q2 == 3) || (q1 == 3 && q2 == 2))
                    || ((q1 == 3 && q2 == 4) || (q1 == 4 && q2 == 3))
                    || (q1 == 2 && q2 == 4 && quadrantTouched[3])
                    || (q1 == 4 && q2 == 2 && quadrantTouched[3])) {

                // CircleLayout.this.post(new FlingRunnable(-1
                // * (velocityX + velocityY)));
                //new Thread(new FlingRunnable(-(velocityX+velocityY))).start();
            } else {
                // the normal rotation
                // CircleLayout.this
                // .post(new FlingRunnable(velocityX + velocityY));
                //new Thread(new FlingRunnable((velocityX+velocityY))).start();
            }

            return true;

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {

            int cur = getInCircle((int)e.getX(),(int)e.getY());
            if(cur!=-1){
                if(mListener!=null){
                    //mListener.onSingleTapUp(cur);
                    mListener.onSingleTapUp(mStones.get(cur).index, mStones.get(cur).angle);
                    LogUtil.v("mStone info: cur: " + cur + "  index:  "+ mStones.get(cur).index + "  mStone name: " + mStones.get(cur).mName);
                    LogUtil.v( "mStone info: index: "+ mStones.get(cur).index + "mStone name: ");
                }

                //Toast.makeText(getContext(), "position:"+String.valueOf(cur), 0).show();
                //Toast.makeText(getContext(), "position:"+String.valueOf(mStones[cur].index), 0).show();

                return true;
            }
            return false;
        }

    }



        public void FlingRunnable(float velocity){

             if( Math.abs(velocity)>=200){
                Message message = Message.obtain();
                message.what = TO_ROTATE_BUTTON;
                message.obj = velocity;
                handler.sendMessage(message);
            }
        }



    /**
     * @return The selected quadrant.
     */
    private static int getQuadrant(double x, double y) {
        if (x >= 0) {
            return y >= 0 ? 1 : 4;
        } else {
        }
        return y >= 0 ? 2 : 3;
    }

    private int m_cur_total_index;
	/*
	 * 旋转菜单按钮
	 */
//	private void rotateButtons(double degree) {
//		
//		if(mTotalStones==null)
//		{
//			return;
//		}
//		
//		for (int i = 0; i < mStones.size(); i++) {
//
//			mStones.get(i).angle += degree;
//			if (mStones.get(i).angle < 0) {
//				mStones.get(i).angle += 360;
//			}else if(mStones.get(i).angle >=360){
//				mStones.get(i).angle -= 360;
//			}
//			
//			
//			if((mStones.get(i).angle>270||(mStones.get(i).angle>=0&&mStones.get(i).angle<180))
//					&&(mStones.get(i).index==0))
//			{
//				
//				if(!mStones.get(i).isFirstShow){
//				
//				} else {
//					if(mStones.get(i).angle>180&&mStones.get(i).angle<270)
//					{
//						mStones.get(i).isFirstShow = false;
//					}
//				}
//				
//				if(m_cur_total_index<mTotalStones.size())
//				{
//
//				} else {
//					m_cur_total_index = 0;
//				
//				}
//				mStones.get(i).bitmap = mTotalStones.get(m_cur_total_index++).bitmap;
//				mStones.get(i).index = m_cur_total_index;
//			}
//			
//			//TODO:hide the stone if angle meet condition
//			if((mStones.get(i).angle>180)&&(mStones.get(i).angle<270))
//			{
//				mStones.get(i).isVisible = false;
//				mStones.get(i).isFirstShow = false;
//				mStones.get(i).index = 0;
//			} else {
//				if((mStones.get(i).index!=0)&&!mStones.get(i).isFirstShow)
//				{
//					mStones.get(i).isVisible = true;
//				}
//			}
//			
//			
//		}
//
//		computeCoordinates();
//		invalidate();
//	}

    public int m_top_in=0;
    public int m_left_in=-1;
    public boolean top_in_end = false;
    public boolean left_in_end= false;
    /*
     * 旋转菜单按钮
     */
    private void rotateButtons(double degree) {

        if(mTotalStones==null)
        {
            return;
        }

        if(mStones==null)
        {
            return;
        }

        if(top_in_end)
        {
            if(degree<0)
            {
                top_in_end = false;
            } else {
                return;
            }
        }

        if(left_in_end)
        {
            if(degree>0)
            {
                left_in_end = false;
            } else {
                return;
            }
        }

        for (int i = 0; i < mStones.size(); i++) {

            mStones.get(i).angle += degree;
            if (mStones.get(i).angle < 0) {
                mStones.get(i).angle += 360;
            }else if(mStones.get(i).angle >=360){
                mStones.get(i).angle -= 360;
            }


            if((mStones.get(i).angle>270||(mStones.get(i).angle>=0&&mStones.get(i).angle<180)))
            {
                if(degree>0)//从右向左划
                {
                    //>300

                    if(mStones.get(i).index==0&&mStones.get(i).angle>270){
                        if(m_top_in<mTotalStones.size())
                        {
                            if(!mStones.get(i).isVisible){
                                mStones.get(i).bitmap = mTotalStones.get(m_top_in).bitmap;
                                mStones.get(i).index = mTotalStones.get(m_top_in).index;
                                mStones.get(i).isVisible = true;
                                m_top_in++;
                            }
                        } else {
                            top_in_end = true;
                        }

                    }

                }else{
                    //<180

                    if(mStones.get(i).index==0&&mStones.get(i).angle<180){
                        if(m_left_in<=0)
                        {
                            left_in_end = true;
                        } else {
                            if(!mStones.get(i).isVisible)
                            {
                                m_left_in--;
                                mStones.get(i).bitmap = mTotalStones.get(m_left_in).bitmap;
                                mStones.get(i).index = mTotalStones.get(m_left_in).index;
                                mStones.get(i).isVisible = true;

                            }
                        }
                    }

                }
            }
            else {
                if(degree>0)//从右向左划
                {

                    if(mStones.get(i).index==0){

                    } else {

                        if(mStones.get(i).index==-1)
                        {
                            m_left_in = 0;
                        } else {
                            m_left_in = mStones.get(i).index ;
                        }
                    }


                } else {
                    if(mStones.get(i).index==0){

                    } else {
                        m_top_in = mStones.get(i).index - 1;
                    }
                }
                mStones.get(i).isVisible = false;
                mStones.get(i).index = 0;
            }

        }

        computeCoordinates();
        invalidate();
    }


    public void autorotateButtons(float velocity) {
        FlingRunnable(velocity);
    }

    @Override
    public void onDraw(Canvas canvas) {
        //画一个白色的圆环
        //canvas.drawCircle(mPointX, mPointY, mRadius, mPaint);

        //将每个菜单画出来
        if(mStones!=null){
            for (int index = 0; index < mStones.size(); index++) {
                if (!mStones.get(index).isVisible)
                    continue;
                drawInCenter(canvas, mStones.get(index).bitmap, mStones.get(index).x,
                        mStones.get(index).y);
            }
        }
    }

    /**
     * 把中心点放到中心处
     *
     * @param canvas
     * @param bitmap
     * @param left
     * @param top
     */
    private void drawInCenter(Canvas canvas, Bitmap bitmap, float left,
                              float top) {
        Rect dst = new Rect();
        dst.left = (int) (left - menuRadius);
        dst.right = (int) (left + menuRadius);
        dst.top = (int) (top - menuRadius);
        dst.bottom = (int) (top + menuRadius);
        canvas.setDrawFilter(pfd);
        canvas.drawBitmap(getCroppedRoundBitmap(bitmap, menuRadius), null, dst, mPaint);
    }

    private int getInCircle(int x, int y) {
        for (int i = 0; i < mStones.size(); i++) {
            BigStone stone = mStones.get(i);
            int mx = (int) stone.x;
            int my = (int) stone.y;
            if (((x - mx) * (x - mx) + (y - my) * (y - my)) < menuRadius
                    * menuRadius) {
                return i;
            }
        }
        return -1;
    }

    public void setOnRoundSpinViewListener(onRoundSpinViewListener listener){
        this.mListener = listener;
    }

    /**
     * 获取裁剪后的圆形图片
     *
     * @param radius
     *            半径
     */
    public Bitmap getCroppedRoundBitmap(Bitmap bmp, int radius) {
        Bitmap scaledSrcBmp;
        int diameter = radius * 2;

        // 为了防止宽高不相等，造成圆形图片变形，因此截取长方形中处于中间位置最大的正方形图片
        int bmpWidth = bmp.getWidth();
        int bmpHeight = bmp.getHeight();
        int squareWidth = 0, squareHeight = 0;
        int x = 0, y = 0;
        Bitmap squareBitmap;
        if (bmpHeight > bmpWidth) {// 高大于宽
            squareWidth = squareHeight = bmpWidth;
            x = 0;
            y = (bmpHeight - bmpWidth) / 2;
            // 截取正方形图片
            squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth,
                    squareHeight);
        } else if (bmpHeight < bmpWidth) {// 宽大于高
            squareWidth = squareHeight = bmpHeight;
            x = (bmpWidth - bmpHeight) / 2;
            y = 0;
            squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth,
                    squareHeight);
        } else {
            squareBitmap = bmp;
        }

        if (squareBitmap.getWidth() != diameter
                || squareBitmap.getHeight() != diameter) {
            scaledSrcBmp = Bitmap.createScaledBitmap(squareBitmap, diameter,
                    diameter, true);

        } else {
            scaledSrcBmp = squareBitmap;
        }
        Bitmap output = Bitmap.createBitmap(scaledSrcBmp.getWidth(),
                scaledSrcBmp.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, scaledSrcBmp.getWidth(),
                scaledSrcBmp.getHeight());

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawCircle(scaledSrcBmp.getWidth() / 2,
                scaledSrcBmp.getHeight() / 2, scaledSrcBmp.getWidth() / 2,
                paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(scaledSrcBmp, rect, rect, paint);
        bmp = null;
        squareBitmap = null;
        scaledSrcBmp = null;
        return output;
    }

}
